Getting the type of an array of T, without specifying T - Type.GetType("T[]")
Posted
by
Merlyn Morgan-Graham
on Stack Overflow
See other posts from Stack Overflow
or by Merlyn Morgan-Graham
Published on 2011-01-12T23:49:10Z
Indexed on
2011/01/12
23:54 UTC
Read the original article
Hit count: 179
I am trying to create a type that refers to an array of a generic type, without specifying the generic type. That is, I would like to do the equivalent of Type.GetType("T[]")
.
I already know how to do this with a non-array type. E.g.
Type.GetType("System.Collections.Generic.IEnumerable`1")
// or
typeof(IEnumerable<>)
Here's some sample code that reproduces the problem.
using System;
using System.Collections.Generic;
public class Program
{
public static void SomeFunc<T>(IEnumerable<T> collection) { }
public static void SomeArrayFunc<T>(T[] collection) { }
static void Main(string[] args)
{
Action<Type> printType = t => Console.WriteLine(t != null ? t.ToString() : "(null)");
Action<string> printFirstParameterType = methodName =>
printType(
typeof(Program).GetMethod(methodName).GetParameters()[0].ParameterType
);
printFirstParameterType("SomeFunc");
printFirstParameterType("SomeArrayFunc");
var iEnumerableT = Type.GetType("System.Collections.Generic.IEnumerable`1");
printType(iEnumerableT);
var iEnumerableTFromTypeof = typeof(IEnumerable<>);
printType(iEnumerableTFromTypeof);
var arrayOfT = Type.GetType("T[]");
printType(arrayOfT); // Prints "(null)"
// ... not even sure where to start for typeof(T[])
}
}
The output is:
System.Collections.Generic.IEnumerable`1[T]
T[]
System.Collections.Generic.IEnumerable`1[T]
System.Collections.Generic.IEnumerable`1[T]
(null)
I'd like to correct that last "(null)".
This will be used to get an overload of a function via reflections by specifying the method signature:
var someMethod = someType.GetMethod("MethodName", new[] { typeOfArrayOfT });
// ... call someMethod.MakeGenericMethod some time later
I've already gotten my code mostly working by filtering the result of GetMethods()
, so this is more of an exercise in knowledge and understanding.
© Stack Overflow or respective owner